/**
 * 浏览器兼容性检测和处理工具
 * 确保在不同浏览器和设备上的兼容性
 */

class CompatibilityManager {
    constructor() {
        this.browserInfo = this.detectBrowser();
        this.features = this.detectFeatures();
        this.polyfills = new Map();
        
        console.log('浏览器兼容性检测完成:', this.browserInfo);
        console.log('特性支持情况:', this.features);
    }
    
    // 检测浏览器信息
    detectBrowser() {
        const ua = navigator.userAgent;
        const browser = {
            name: 'unknown',
            version: 'unknown',
            engine: 'unknown',
            mobile: /Mobile|Android|iPhone|iPad/.test(ua),
            ios: /iPhone|iPad|iPod/.test(ua),
            android: /Android/.test(ua),
            chrome: /Chrome/.test(ua),
            firefox: /Firefox/.test(ua),
            safari: /Safari/.test(ua) && !/Chrome/.test(ua),
            edge: /Edge/.test(ua),
            ie: /MSIE|Trident/.test(ua)
        };
        
        // 检测浏览器名称和版本
        if (browser.chrome) {
            const match = ua.match(/Chrome\/(\d+)/);
            browser.name = 'Chrome';
            browser.version = match ? match[1] : 'unknown';
            browser.engine = 'Blink';
        } else if (browser.firefox) {
            const match = ua.match(/Firefox\/(\d+)/);
            browser.name = 'Firefox';
            browser.version = match ? match[1] : 'unknown';
            browser.engine = 'Gecko';
        } else if (browser.safari) {
            const match = ua.match(/Version\/(\d+)/);
            browser.name = 'Safari';
            browser.version = match ? match[1] : 'unknown';
            browser.engine = 'WebKit';
        } else if (browser.edge) {
            const match = ua.match(/Edge\/(\d+)/);
            browser.name = 'Edge';
            browser.version = match ? match[1] : 'unknown';
            browser.engine = 'EdgeHTML';
        } else if (browser.ie) {
            browser.name = 'Internet Explorer';
            browser.engine = 'Trident';
            browser.legacy = true;
        }
        
        return browser;
    }
    
    // 检测浏览器特性支持
    detectFeatures() {
        return {
            // ES6+ 特性
            es6: {
                arrow: this.testFeature(() => eval('(() => true)()')),
                const: this.testFeature(() => eval('const x = 1; true')),
                let: this.testFeature(() => eval('let x = 1; true')),
                template: this.testFeature(() => eval('`template`')),
                destructuring: this.testFeature(() => eval('const [a] = [1]; true')),
                spread: this.testFeature(() => eval('const a = [...[1]]; true')),
                classes: this.testFeature(() => eval('class A {}; true')),
                modules: 'import' in document.createElement('script'),
                promises: typeof Promise !== 'undefined',
                asyncAwait: this.testFeature(() => eval('async function f() { await 1; }; true'))
            },
            
            // Web APIs
            apis: {
                fetch: typeof fetch !== 'undefined',
                intersectionObserver: 'IntersectionObserver' in window,
                resizeObserver: 'ResizeObserver' in window,
                mutationObserver: 'MutationObserver' in window,
                serviceWorker: 'serviceWorker' in navigator,
                webWorkers: typeof Worker !== 'undefined',
                localStorage: this.testLocalStorage(),
                sessionStorage: this.testSessionStorage(),
                indexedDB: 'indexedDB' in window,
                webGL: this.testWebGL(),
                webGL2: this.testWebGL2(),
                canvas: this.testCanvas(),
                svg: this.testSVG()
            },
            
            // PDF.js 相关
            pdf: {
                arrayBuffer: 'ArrayBuffer' in window,
                uint8Array: 'Uint8Array' in window,
                blob: 'Blob' in window,
                fileReader: 'FileReader' in window,
                url: 'URL' in window,
                createObjectURL: 'URL' in window && 'createObjectURL' in URL
            },
            
            // 现代特性
            modern: {
                createImageBitmap: 'createImageBitmap' in window,
                offscreenCanvas: 'OffscreenCanvas' in window,
                requestIdleCallback: 'requestIdleCallback' in window,
                requestAnimationFrame: 'requestAnimationFrame' in window,
                performance: 'performance' in window,
                deviceMemory: 'deviceMemory' in navigator,
                connection: 'connection' in navigator,
                vibrate: 'vibrate' in navigator
            },
            
            // CSS 特性
            css: {
                flexbox: this.testCSS('display', 'flex'),
                grid: this.testCSS('display', 'grid'),
                customProperties: this.testCSS('--test', 'value'),
                transforms: this.testCSS('transform', 'translateX(1px)'),
                transitions: this.testCSS('transition', 'all 1s'),
                animations: this.testCSS('animation', 'test 1s'),
                backdropFilter: this.testCSS('backdrop-filter', 'blur(1px)'),
                objectFit: this.testCSS('object-fit', 'cover')
            }
        };
    }
    
    // 测试特性支持
    testFeature(fn) {
        try {
            return fn();
        } catch (e) {
            return false;
        }
    }
    
    // 测试本地存储
    testLocalStorage() {
        try {
            const test = 'test';
            localStorage.setItem(test, test);
            localStorage.removeItem(test);
            return true;
        } catch (e) {
            return false;
        }
    }
    
    // 测试会话存储
    testSessionStorage() {
        try {
            const test = 'test';
            sessionStorage.setItem(test, test);
            sessionStorage.removeItem(test);
            return true;
        } catch (e) {
            return false;
        }
    }
    
    // 测试WebGL支持
    testWebGL() {
        try {
            const canvas = document.createElement('canvas');
            const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
            return !!gl;
        } catch (e) {
            return false;
        }
    }
    
    // 测试WebGL2支持
    testWebGL2() {
        try {
            const canvas = document.createElement('canvas');
            const gl = canvas.getContext('webgl2');
            return !!gl;
        } catch (e) {
            return false;
        }
    }
    
    // 测试Canvas支持
    testCanvas() {
        try {
            const canvas = document.createElement('canvas');
            return !!(canvas.getContext && canvas.getContext('2d'));
        } catch (e) {
            return false;
        }
    }
    
    // 测试SVG支持
    testSVG() {
        return !!(document.createElementNS && document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect);
    }
    
    // 测试CSS特性
    testCSS(property, value) {
        try {
            const element = document.createElement('div');
            element.style[property] = value;
            return element.style[property] === value;
        } catch (e) {
            return false;
        }
    }
    
    // 检查是否为旧版浏览器
    isLegacyBrowser() {
        return this.browserInfo.ie || 
               (this.browserInfo.chrome && parseInt(this.browserInfo.version) < 60) ||
               (this.browserInfo.firefox && parseInt(this.browserInfo.version) < 55) ||
               (this.browserInfo.safari && parseInt(this.browserInfo.version) < 12);
    }
    
    // 检查是否需要polyfill
    needsPolyfill(feature) {
        const path = feature.split('.');
        let current = this.features;
        
        for (const key of path) {
            if (!current[key]) return true;
            current = current[key];
        }
        
        return !current;
    }
    
    // 加载polyfill
    async loadPolyfill(name, url) {
        if (this.polyfills.has(name)) {
            return this.polyfills.get(name);
        }
        
        const promise = new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = url;
            script.onload = () => resolve();
            script.onerror = () => reject(new Error(`Failed to load polyfill: ${name}`));
            document.head.appendChild(script);
        });
        
        this.polyfills.set(name, promise);
        return promise;
    }
    
    // 获取兼容性报告
    getCompatibilityReport() {
        const issues = [];
        const warnings = [];
        const recommendations = [];
        
        // 检查关键特性
        if (!this.features.apis.canvas) {
            issues.push('Canvas API 不支持，PDF渲染将无法工作');
        }
        
        if (!this.features.pdf.arrayBuffer) {
            issues.push('ArrayBuffer 不支持，PDF加载将失败');
        }
        
        if (!this.features.apis.localStorage) {
            warnings.push('LocalStorage 不支持，无法保存用户设置');
        }
        
        if (!this.features.es6.promises) {
            issues.push('Promise 不支持，需要polyfill');
        }
        
        if (!this.features.apis.fetch) {
            warnings.push('Fetch API 不支持，将使用XMLHttpRequest降级');
        }
        
        if (this.isLegacyBrowser()) {
            recommendations.push('建议升级到更新版本的浏览器以获得最佳体验');
        }
        
        if (!this.features.modern.createImageBitmap) {
            recommendations.push('浏览器不支持ImageBitmap，性能可能受影响');
        }
        
        return {
            browser: this.browserInfo,
            features: this.features,
            issues,
            warnings,
            recommendations,
            compatible: issues.length === 0
        };
    }
}

// 全局兼容性管理器实例
window.CompatibilityManager = CompatibilityManager;
